#pragma once

#include <iostream>
#include <string>
#include <cstring>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "err.hpp"

static const int gbacklog = 5;

class Sock
{
public:
    static int creatSock()
    {
        // 1.创建套接字,使用tcp协议
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            LogMessage(FATAL, "creat socket error");
            exit(SOCKET_ERR);
        }
        LogMessage(NORMAL, "creat sockfd success:%d", sockfd);

        // 设置地址复用和端口复用，保证服务器关闭后可以重新连接
        int opt = 1;
        setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

        return sockfd;
    }

    static void Bind(int sock, int port)
    {
        // 2.bind绑定自己的网络信息，sockfd与IP和port
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));

        local.sin_family = PF_INET; // AF_INET就是PF_INET
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LogMessage(FATAL, "server bind error");
            exit(BIND_ERR);
        }
        LogMessage(NORMAL, "server bind success");
    }

    static void Listen(int sock)
    {
        // 3. tcp需要建立连接！ 设置监听状态，获取新连接
        if (listen(sock, gbacklog) == -1)
        {
            LogMessage(FATAL, "server listen error");
            exit(LISTEN_ERR);
        }
        LogMessage(NORMAL, "server listen success");
    }

    static int Accept(int listensock, std::string *clientip, uint16_t *clientport)
    {
        // 4. tcpserver获取新连接
        struct sockaddr_in peer;
        socklen_t peerlen = sizeof(peer);
        memset(&peer, 0, sizeof(peer));
        LogMessage(DEBUG, "listensockfd:%d", listensock);
        int sockfd = accept(listensock, (sockaddr *)(&peer), &peerlen); // 获取是sockfd用于通信

        if (sockfd < 0)
        {
            LogMessage(ERROR, "server accept error, re accept");
        }
        else
        {
            LogMessage(NORMAL, "server accept a new link success,get new sock:%d", sockfd);
            *clientport = ntohs(peer.sin_port);
            *clientip = inet_ntoa(peer.sin_addr);
        }
        return sockfd;
    }
};